﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Script.Serialization;
using System.Windows.Forms;
using ErpToCrm.Model;
using ErpToCrm.Config;
using ErpToCrm.DataMapping;
using System.ComponentModel;
using System.Threading;

namespace ErpToCrm
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private List<BackgroundWorker> workerList = null;

        public List<BackgroundWorker> WorkerList
        {
            get
            {
                if (workerList == null)
                {
                    workerList = new List<BackgroundWorker>();
                    for (int i = 0; i < 10; i++)
                    {
                        BackgroundWorker m_BackgroundWorker = new BackgroundWorker();
                        m_BackgroundWorker.WorkerReportsProgress = true;
                        m_BackgroundWorker.WorkerSupportsCancellation = true;
                        // m_BackgroundWorker.DoWork += new DoWorkEventHandler(DoWorkXS);
                        m_BackgroundWorker.DoWork += new DoWorkEventHandler(DoWorkZL);
                        m_BackgroundWorker.ProgressChanged += new ProgressChangedEventHandler(UpdateProgress);
                        m_BackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompletedWork);
                        workerList.Add(m_BackgroundWorker);
                    }
                }
                return workerList;
            }

        }


        /// <summary>
        /// 销售合同
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            this.button2.Enabled = false;
            JavaScriptSerializer jss = new JavaScriptSerializer();
            jss.MaxJsonLength = Int32.MaxValue;


            // 0.获取erp销售数据总count，获取每页数据
            string erp_data_string_xs = RestClient.Get(UriConfig.ERP_BASE + UriConfig.ERP_SOURCE_XS_COUNT);
            ErpResult<CountResult> erp_data_result_xs = jss.Deserialize<ErpResult<CountResult>>(erp_data_string_xs);

            if (erp_data_result_xs.result)
            {
                // 总数
                int total = Convert.ToInt32(erp_data_result_xs.data[0].COUNT);
                // 每页数据
                int page_num = Convert.ToInt32(total / 10);
                // 循环调用
                for (int i = 0; i < 10; i++)
                {
                    WorkArgs workArgs = new WorkArgs();
                    workArgs.page_start = i * page_num + 1;
                    if (i == 9)
                    {
                        workArgs.page_end = total;
                    }
                    else
                    {
                        workArgs.page_end = (i + 1) * page_num;
                    }
                    workArgs.id = i;
                    Thread.Sleep(1000);
                    WorkerList[i].RunWorkerAsync(workArgs);
                }
            }
            else
            {
                OprateError();
            }
        }

        /// <summary>
        /// 租赁合同
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            this.button1.Enabled = false;
/*            JavaScriptSerializer jss = new JavaScriptSerializer();
            jss.MaxJsonLength = Int32.MaxValue;

            // 2.获取erp租赁数据
            string erp_data_string_zl = RestClient.Get(UriConfig.ERP_BASE + UriConfig.ERP_SOURCE_ZL);
            ErpResult<ErpZL_Data> erp_data_result_zl = jss.Deserialize<ErpResult<ErpZL_Data>>(erp_data_string_zl);
            if (erp_data_result_zl.result)
            {
                // 2.调用联东登录接口
                string login_result_string = RestClient.Get(UriConfig.CRM_BASE + UriConfig.CRM_LOGIN);
                CrmUser crm_login_result = jss.Deserialize<CrmUser>(login_result_string);
                if (crm_login_result.result)
                {
                    // 3.数据映射
                    List<CrmDataZL> list = MappingService.MappingDataZL(erp_data_result_zl);
                    // 4.查询字段，转换数据
                    this.ExecuteDataZL(list, crm_login_result.binding);
                }
                else
                {
                    this.OprateError();
                }
            }
            else
            {
                this.OprateError();
            }*/

            JavaScriptSerializer jss = new JavaScriptSerializer();
            jss.MaxJsonLength = Int32.MaxValue;


            // 0.获取erp销售数据总count，获取每页数据
            string erp_data_string_zl = RestClient.Get(UriConfig.ERP_BASE + UriConfig.ERP_SOURCE_ZL_COUNT);
            ErpResult<CountResult> erp_data_result_zl = jss.Deserialize<ErpResult<CountResult>>(erp_data_string_zl);

            if (erp_data_result_zl.result)
            {
                // 总数
                int total = Convert.ToInt32(erp_data_result_zl.data[0].COUNT);
                // 每页数据
                int page_num = Convert.ToInt32(total / 10);
                // 循环调用
                for (int i = 0; i < 10; i++)
                {
                    WorkArgs workArgs = new WorkArgs();
                    workArgs.page_start = i * page_num + 1;
                    if (i == 9)
                    {
                        workArgs.page_end = total;
                    }
                    else
                    {
                        workArgs.page_end = (i + 1) * page_num;
                    }
                    workArgs.id = i;
                    Thread.Sleep(1000);
                    WorkerList[i].RunWorkerAsync(workArgs);
                }
            }
            else
            {
                OprateError();
            }

        }

        private void UpdateProgress(object sender, ProgressChangedEventArgs e)
        {
            int progress = e.ProgressPercentage;

            switch (Convert.ToInt32(e.UserState))
            {
                case 0:
                    label1.Text = "第1个线程:" + progress.ToString() + "%";
                    break;
                case 1:
                    label2.Text = "第2个线程:" + progress.ToString() + "%";
                    break;
                case 2:
                    label3.Text = "第3个线程:" + progress.ToString() + "%";
                    break;
                case 3:
                    label4.Text = "第4个线程:" + progress.ToString() + "%";
                    break;
                case 4:
                    label5.Text = "第5个线程:" + progress.ToString() + "%";
                    break;
                case 5:
                    label6.Text = "第6个线程:" + progress.ToString() + "%";
                    break;
                case 6:
                    label7.Text = "第7个线程:" + progress.ToString() + "%";
                    break;
                case 7:
                    label8.Text = "第8个线程:" + progress.ToString() + "%";
                    break;
                case 8:
                    label9.Text = "第9个线程:" + progress.ToString() + "%";
                    break;
                case 9:
                    label10.Text = "第10个线程:" + progress.ToString() + "%";
                    break;
                default:
                    break;
            }
        }

        private void CompletedWork(object sender, RunWorkerCompletedEventArgs e)
        {
            switch (Convert.ToInt32(e.UserState))
            {
                case 0:
                    label1.Text = "第1个线程:" + 100 + "%";
                    break;
                case 1:
                    label2.Text = "第2个线程:" + 100 + "%";
                    break;
                case 2:
                    label3.Text = "第3个线程:" + 100 + "%";
                    break;
                case 3:
                    label4.Text = "第4个线程:" + 100 + "%";
                    break;
                case 4:
                    label5.Text = "第5个线程:" + 100 + "%";
                    break;
                case 5:
                    label6.Text = "第6个线程:" + 100 + "%";
                    break;
                case 6:
                    label7.Text = "第7个线程:" + 100 + "%";
                    break;
                case 7:
                    label8.Text = "第8个线程:" + 100 + "%";
                    break;
                case 8:
                    label9.Text = "第9个线程:" + 100 + "%";
                    break;
                case 9:
                    label10.Text = "第10个线程:" + 100 + "%";
                    break;
                default:
                    break;
            }
        }

        private void DoWorkXS(object sender, DoWorkEventArgs e)
        {
            try
            {
                BackgroundWorker bw = sender as BackgroundWorker;
                WorkArgs workArgs = e.Argument as WorkArgs;

                JavaScriptSerializer jss = new JavaScriptSerializer();
                jss.MaxJsonLength = Int32.MaxValue;
                // 1.获取erp销售数据
                string erp_data_string_xs = RestClient.Get(UriConfig.ERP_BASE + string.Format(UriConfig.ERP_QUERY_XS_PAGE, workArgs.page_end, workArgs.page_start));
                ErpResult<ErpXS_Data> erp_data_result_xs = jss.Deserialize<ErpResult<ErpXS_Data>>(erp_data_string_xs);
                if (erp_data_result_xs.result)
                {
                    // 2.调用联东登录接口
                    string login_result_string = RestClient.Get(UriConfig.CRM_BASE + UriConfig.CRM_LOGIN);
                    CrmUser crm_login_result = jss.Deserialize<CrmUser>(login_result_string);
                    if (crm_login_result.result)
                    {
                        // 3.数据映射
                        List<CrmDataXS> list = MappingService.MappingDataXS(erp_data_result_xs.data);
                        // 4.查询字段，转换数据
                        ExecuteDataXS(list, crm_login_result.binding, bw, workArgs.id);

                    }
                    else
                    {
                        OprateError();
                    }
                }
                else
                {
                    OprateError();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }

        private void DoWorkZL(object sender, DoWorkEventArgs e)
        {
            try
            {
                BackgroundWorker bw = sender as BackgroundWorker;
                WorkArgs workArgs = e.Argument as WorkArgs;

                JavaScriptSerializer jss = new JavaScriptSerializer();
                jss.MaxJsonLength = Int32.MaxValue;
                // 1.获取erp租赁数据
                string erp_data_string_zl = RestClient.Get(UriConfig.ERP_BASE + string.Format(UriConfig.ERP_QUERY_ZL_PAGE, workArgs.page_end, workArgs.page_start));
                ErpResult<ErpZL_Data> erp_data_result_zl = jss.Deserialize<ErpResult<ErpZL_Data>>(erp_data_string_zl);
                if (erp_data_result_zl.result)
                {
                    // 2.调用联东登录接口
                    string login_result_string = RestClient.Get(UriConfig.CRM_BASE + UriConfig.CRM_LOGIN);
                    CrmUser crm_login_result = jss.Deserialize<CrmUser>(login_result_string);
                    if (crm_login_result.result)
                    {
                        // 3.数据映射
                        List<CrmDataZL> list = MappingService.MappingDataZL(erp_data_result_zl.data);
                        // 4.查询字段，转换数据
                        ExecuteDataZL(list, crm_login_result.binding, bw, workArgs.id);

                    }
                    else
                    {
                        OprateError();
                    }
                }
                else
                {
                    OprateError();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }


        /// <summary>
        /// 执行销售合同数据处理
        /// </summary>
        /// <param name="data"></param>
        /// <param name="binding"></param>
        /// <returns></returns>
        private List<CrmDataXS> ExecuteDataXS(List<CrmDataXS> data, string binding, BackgroundWorker worker, object args)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            jss.MaxJsonLength = Int32.MaxValue;
            for (int i = 0; i < data.Count; i++)
            {
                double a = i;
                double b = data.Count;
                worker.ReportProgress((int)((a / b) * 100), args);
                // 1.查询房产主键
                string string1 = "select id from fc where fczj ='" + data[i].fcmc.Trim() + "'&binding=" + binding;
                string string1_result = RestClient.Get(UriConfig.CRM_BASE + UriConfig.CRM_CQLQUERY_BASE + string1);
                CrmQueryResult cq_result1 = jss.Deserialize<CrmQueryResult>(string1_result);
                if (cq_result1.result)
                {
                    data[i].fcmc = cq_result1.data.Count > 0 ? cq_result1.data[0].id : "";
                }
                else
                {
                    this.OprateError();
                }

                // 2.查询客户名称
                string string2 = "select id from Account where nckhzj ='" + data[i].khmc.Trim() + "'&binding=" + binding;
                string string2_result = RestClient.Get(UriConfig.CRM_BASE + UriConfig.CRM_CQLQUERY_BASE + string2);
                CrmQueryResult cq_result2 = jss.Deserialize<CrmQueryResult>(string2_result);
                if (cq_result2.result)
                {
                    data[i].khmc = cq_result2.data.Count > 0 ? cq_result2.data[0].id : "";
                }
                else
                {
                    this.OprateError();
                }

                // 3.查询公司主键
                string string3 = "select gsmc from zsxm where gszj ='" + data[i].skgsmc.Trim() + "'&binding=" + binding;
                string string3_result = RestClient.Get(UriConfig.CRM_BASE + UriConfig.CRM_CQLQUERY_BASE + string3);
                CrmQueryResult cq_result3 = jss.Deserialize<CrmQueryResult>(string3_result);
                if (cq_result3.result)
                {
                    data[i].skgsmc = cq_result3.data.Count > 0 ? cq_result3.data[0].id : "";
                }
                else
                {
                    this.OprateError();
                }

                // 4.所有人
                if (data[i].ownerid != "")
                {
                    // 4.1 查询jobnumber
                    string string4_result = RestClient.Get(UriConfig.ERP_BASE + UriConfig.ERP_QUERY_JOBNUMBER + "'" + data[i].ownerid + "'");

                    string jobnumber = "";
                    ErpResult<ErpPsndoc> cq_result4 = jss.Deserialize<ErpResult<ErpPsndoc>>(string4_result);
                    if (cq_result4.result)
                    {
                        jobnumber = cq_result4.data.Count > 0 ? cq_result4.data[0].jobnumber : "";
                    }
                    else
                    {
                        this.OprateError();
                    }

                    if (jobnumber != "")
                    {
                        // 4.2 查询ccuser的id
                        string string5 = "select id from ccuser where employeenum ='" + jobnumber + "'&binding=" + binding;
                        string string5_result = RestClient.Get(UriConfig.CRM_BASE + UriConfig.CRM_CQLQUERY_BASE + string5);
                        CrmQueryResult cq_result5 = jss.Deserialize<CrmQueryResult>(string5_result);
                        if (cq_result5.result)
                        {
                            data[i].ownerid = cq_result5.data.Count > 0 ? cq_result5.data[0].id : "";
                        }
                        else
                        {
                            this.OprateError();
                        }
                    }
                    else
                    {
                        data[i].ownerid = UriConfig.CRM_SYSTEM_ID;
                    }
                }
                else
                {
                    data[i].ownerid = UriConfig.CRM_SYSTEM_ID;
                }


                // 5.调用insert插入数据 销售合同主表
                var jsonSetting = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };

                var dataStr = JsonConvert.SerializeObject(data[i], Formatting.Indented, jsonSetting);

                //string dataStr = jss.Serialize(data[i]);
                dataStr = "[" + dataStr + "]";
                string insertStr = binding + "&data=" + HttpUtility.UrlEncode(dataStr);
                string insertStr_result = RestClient.Get(UriConfig.CRM_BASE + UriConfig.CRM_INSERT_CONTRAT_XS + insertStr);
                // CrmInsertResult insert_result = jss.Deserialize<CrmInsertResult>(insertStr_result);

                // 6.调用insert插入数据 小产证子表
                CrmXCZ crmXCZ = new CrmXCZ();
                crmXCZ.xshtmc = getID(insertStr_result);
                crmXCZ.czzt = data[i].textdef7;
                int flag = 0;
                if (crmXCZ.czzt.Length > 0)
                {
                    flag = 1;
                }
                crmXCZ.dydjzt = data[i].textdef8;
                var datasStr_xcz = JsonConvert.SerializeObject(crmXCZ, Formatting.Indented, jsonSetting);
                datasStr_xcz = "[" + datasStr_xcz + "]";
                string insertStr_xcz = binding + "&data=" + HttpUtility.UrlEncode(datasStr_xcz);
                string insertStr_xcz_result = RestClient.Get(UriConfig.CRM_BASE + UriConfig.CRM_INSERT_CONTRAT_XCZ + insertStr_xcz);
                CrmInsertResult insert_result_xcz = jss.Deserialize<CrmInsertResult>(insertStr_xcz_result);
            }

            return data;
        }

        /// <summary>
        /// 领导让出活，这个实在没时间调了
        /// </summary>
        /// <returns></returns>
        private string getID(string result)
        {
            int start = result.LastIndexOf(":");
            string t1 = result.Substring(start);
            string t2 = t1.Substring(t1.IndexOf("\"") + 1);
            string t3 = t2.Substring(0, t2.IndexOf("\""));
            return t3;
        }

        /// <summary>
        /// 执行租赁合同数据处理
        /// </summary>
        /// <param name="data"></param>
        /// <param name="binding"></param>
        /// <returns></returns>
        private List<CrmDataZL> ExecuteDataZL(List<CrmDataZL> data, string binding, BackgroundWorker worker, object args)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            jss.MaxJsonLength = Int32.MaxValue;
            for (int i = 0; i < data.Count; i++)
            {
                double a = i;
                double b = data.Count;
                worker.ReportProgress((int)((a / b) * 100), args);
                // 1.查询房产主键
                string string1 = "select id from fc where fczj ='" + data[i].fcmc.Trim() + "'&binding=" + binding;
                string string1_result = RestClient.Get(UriConfig.CRM_BASE + UriConfig.CRM_CQLQUERY_BASE + string1);
                CrmQueryResult cq_result1 = jss.Deserialize<CrmQueryResult>(string1_result);
                if (cq_result1.result)
                {
                    data[i].fcmc = cq_result1.data.Count > 0 ? cq_result1.data[0].id : "";
                }
                else
                {
                    this.OprateError();
                }

                // 2.查询客户名称
                string string2 = "select id from Account where nckhzj ='" + data[i].khmc.Trim() + "'&binding=" + binding;
                string string2_result = RestClient.Get(UriConfig.CRM_BASE + UriConfig.CRM_CQLQUERY_BASE + string2);
                CrmQueryResult cq_result2 = jss.Deserialize<CrmQueryResult>(string2_result);
                if (cq_result2.result)
                {
                    data[i].khmc = cq_result2.data.Count > 0 ? cq_result2.data[0].id : "";
                }
                else
                {
                    this.OprateError();
                }

                // 3.查询公司主键
                string string3 = "select gsmc from zsxm where gszj ='" + data[i].skgsmc.Trim() + "'&binding=" + binding;
                string string3_result = RestClient.Get(UriConfig.CRM_BASE + UriConfig.CRM_CQLQUERY_BASE + string3);
                CrmQueryResult cq_result3 = jss.Deserialize<CrmQueryResult>(string3_result);
                if (cq_result3.result)
                {
                    data[i].skgsmc = cq_result3.data.Count > 0 ? cq_result3.data[0].id : "";
                }
                else
                {
                    this.OprateError();
                }

                // 4.所有人

                if (data[i].ownerid != "")
                {
                    // 4.1 查询jobnumber
                    string string4_result = RestClient.Get(UriConfig.ERP_BASE + UriConfig.ERP_QUERY_JOBNUMBER + "'" + data[i].ownerid + "'");

                    string jobnumber = "";
                    ErpResult<ErpPsndoc> cq_result4 = jss.Deserialize<ErpResult<ErpPsndoc>>(string4_result);
                    if (cq_result4.result)
                    {
                        jobnumber = cq_result4.data.Count > 0 ? cq_result4.data[0].jobnumber : "";
                    }
                    else
                    {
                        this.OprateError();
                    }

                    if (jobnumber != "")
                    {
                        // 4.2 查询ccuser的id
                        string string5 = "select id from ccuser where employeenum ='" + jobnumber + "'&binding=" + binding;
                        string string5_result = RestClient.Get(UriConfig.CRM_BASE + UriConfig.CRM_CQLQUERY_BASE + string5);
                        CrmQueryResult cq_result5 = jss.Deserialize<CrmQueryResult>(string5_result);
                        if (cq_result5.result)
                        {
                            data[i].ownerid = cq_result5.data.Count > 0 ? cq_result5.data[0].id : "";
                        }
                        else
                        {
                            this.OprateError();
                        }
                    }
                    else
                    {
                        data[i].ownerid = UriConfig.CRM_SYSTEM_ID;
                    }

                }
                else
                {
                    data[i].ownerid = UriConfig.CRM_SYSTEM_ID;
                }



                // 5.调用insert插入数据
                var jsonSetting = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };

                var dataStr = JsonConvert.SerializeObject(data[i], Formatting.Indented, jsonSetting);

                //string dataStr = jss.Serialize(data[i]);
                dataStr = "[" + dataStr + "]";
                string insertStr = binding + "&data=" + HttpUtility.UrlEncode(dataStr);
                string insertStr_result = RestClient.Get(UriConfig.CRM_BASE + UriConfig.CRM_INSERT_CONTRAT_ZL + insertStr);
                CrmQueryResult insert_result = jss.Deserialize<CrmQueryResult>(insertStr_result);
                if (insert_result.result == false) 
                {
                    OprateError();
                }
            }

            return data;
        }

        private void OprateError()
        {
            // 返回值失败，需要处理
        }

    }
}
